package com.huang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huang.anno.ResponseResult;
import com.huang.entity.IotDeviceAttribute;
import com.huang.entity.User;
import com.huang.mapper.IotDeviceAttributeMapper;
import com.huang.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 黄自祥
 * @date 2022/05/03 14:13
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserMapper userMapper;

    @Autowired
    IotDeviceAttributeMapper iotDeviceAttributeMapper;
    @ResponseResult
    @RequestMapping("/getUser")
    public List<User> getUser(User user){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getSex, user.getSex());
        List<User> users = userMapper.selectList(queryWrapper);
//        Page<User> userPage = userMapper.selectPage(new Page<>(), );
        log.info("haha");
        return users;
    }


    @RequestMapping("/findDeviceAttributeListByQueryDto")
    List<IotDeviceAttribute> findDeviceAttributeListByQueryDto(){
        // 查询所有的
        List<IotDeviceAttribute> IotDeviceAttributeList =
                iotDeviceAttributeMapper.findDeviceAttributeListByQueryDto();
        // 查询所有parentId不为null即根节点
        Map<Long, List<IotDeviceAttribute>> collect =
                IotDeviceAttributeList.stream().filter(t->t.getParentId()!=null).collect(Collectors.groupingBy(IotDeviceAttribute::getParentId));
        // 查询所有根节点
        List<IotDeviceAttribute>root =
                IotDeviceAttributeList.stream().filter(t->t.getParentId()==null).collect(Collectors.toList());
        for(IotDeviceAttribute iotDeviceAttribute:root){
            iotDeviceAttribute.setChildren(getChildren(iotDeviceAttribute,collect));
        }

        return root;
    }



    private List<IotDeviceAttribute> getChildren(IotDeviceAttribute deviceTreeT, Map<Long, List<IotDeviceAttribute>> collect) {
        List<IotDeviceAttribute> deviceTrees=collect.get(deviceTreeT.getId());
        if(deviceTrees!=null){
            for(IotDeviceAttribute deviceTree:deviceTrees){
                deviceTree.setChildren(getChildren(deviceTree,collect));
            }
        }
        return deviceTrees;
    }


}
